import os
import os.path
import signal
import subprocess
import time
from django.core.management import base

def safekill(pidfile, pid, level):
    try:
        os.kill(pid, level)
    except OSError:
        print 'Daemon appears dead, removing pidfile.'
        os.remove(pidfile)
        return False
    return True

def stopdaemon():
    from django.conf import settings

    pidfile = settings.DAEMON_PIDFILE

    if settings.DAEMON_NO_BACKGROUND:
        print 'Not configured as a daemon, nothing to do.'
    elif os.path.exists(pidfile):
        pid = int(open(pidfile).read())
        tries = 4
        print 'Sending SIGTERM and waiting for termination...'
        if not safekill(pidfile, pid, signal.SIGTERM):
            return
        while tries > 0 and safekill(pidfile, pid, signal.SIGTERM):
            tries -= 1
            time.sleep(0.5)
        if tries == 0:
            print 'Daemon not dying, sending SIGKILL.'
            safekill(pid, signals.SIGKILL)
    else:
        print "PID file doesn't exists, nothing to do."

class Command(base.BaseCommand):
    can_import_settings = True
    help = 'Stop the music processing daemon'

    def handle(self, *args, **kwargs):
        stopdaemon()
